<template>
  <div class="realtime-monitor">
    <!-- 实时数据概览 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6" v-for="(item, index) in realtimeData" :key="index">
        <el-card shadow="hover" class="data-card" :class="{ 'alert': item.alert }">
          <template #header>
            <div class="card-header">
              <span>{{ item.title }}</span>
              <el-tag :type="item.trend > 0 ? 'success' : 'danger'" size="small">
                {{ item.trend > 0 ? '+' : '' }}{{ item.trend }}%
              </el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">{{ item.value }}</div>
            <div class="trend">
              <span>实时更新</span>
              <span class="update-time">{{ item.updateTime }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时监控图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>实时交易监控</span>
              <div class="header-actions">
                <el-radio-group v-model="monitorType" size="small">
                  <el-radio-button label="sales">销售额</el-radio-button>
                  <el-radio-button label="orders">订单数</el-radio-button>
                  <el-radio-button label="users">用户数</el-radio-button>
                </el-radio-group>
                <el-switch
                  v-model="autoRefresh"
                  active-text="自动刷新"
                  @change="handleAutoRefreshChange"
                />
              </div>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="realtimeChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>实时告警</span>
              <el-button type="primary" link @click="handleViewAllAlerts">
                查看全部
              </el-button>
            </div>
          </template>
          <div class="alert-list">
            <div v-for="(alert, index) in alerts" :key="index" class="alert-item" :class="alert.level">
              <el-icon><Warning /></el-icon>
              <div class="alert-content">
                <div class="alert-title">{{ alert.title }}</div>
                <div class="alert-time">{{ alert.time }}</div>
              </div>
              <el-button type="primary" link @click="handleAlertAction(alert)">
                处理
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时热力图 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>实时访问热力图</span>
          <el-select v-model="heatmapType" size="small">
            <el-option label="访问量" value="visits" />
            <el-option label="交易量" value="transactions" />
            <el-option label="转化率" value="conversion" />
          </el-select>
        </div>
      </template>
      <div class="chart-container">
        <v-chart class="chart" :option="heatmapOption" autoresize />
      </div>
    </el-card>

    <!-- 告警设置对话框 -->
    <el-dialog
      v-model="alertSettingVisible"
      title="告警设置"
      width="600px"
    >
      <el-form :model="alertSettings" label-width="120px">
        <el-form-item label="告警阈值">
          <el-input-number v-model="alertSettings.threshold" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="告警方式">
          <el-checkbox-group v-model="alertSettings.methods">
            <el-checkbox label="email">邮件通知</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
            <el-checkbox label="system">系统通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="告警时间">
          <el-time-picker
            v-model="alertSettings.timeRange"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="alertSettingVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAlertSettings">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, HeatmapChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
  VisualMapComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { Warning } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getRealtimeData, getRealtimeChart, getAlerts, updateAlertSettings } from '@/api/statistics'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  HeatmapChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
  VisualMapComponent
])

// 实时数据
const realtimeData = ref([
  {
    title: '实时销售额',
    value: '¥0',
    trend: 0,
    updateTime: '--:--:--',
    alert: false
  },
  {
    title: '实时订单数',
    value: '0',
    trend: 0,
    updateTime: '--:--:--',
    alert: false
  },
  {
    title: '实时用户数',
    value: '0',
    trend: 0,
    updateTime: '--:--:--',
    alert: false
  },
  {
    title: '实时转化率',
    value: '0%',
    trend: 0,
    updateTime: '--:--:--',
    alert: false
  }
])

// 监控类型
const monitorType = ref('sales')
const autoRefresh = ref(true)
const refreshInterval = ref(null)

// 告警列表
const alerts = ref([])
const alertSettingVisible = ref(false)
const alertSettings = ref({
  threshold: 80,
  methods: ['system'],
  timeRange: []
})

// 热力图类型
const heatmapType = ref('visits')

// 实时图表配置
const realtimeChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  legend: {
    data: ['实时数据', '历史平均']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '实时数据',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(64,158,255,0.3)'
          }, {
            offset: 1,
            color: 'rgba(64,158,255,0.1)'
          }]
        }
      }
    },
    {
      name: '历史平均',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#909399'
      },
      lineStyle: {
        type: 'dashed'
      }
    }
  ]
}))

// 热力图配置
const heatmapOption = computed(() => ({
  tooltip: {
    position: 'top'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: Array.from({ length: 24 }, (_, i) => `${i}:00`),
    splitArea: {
      show: true
    }
  },
  yAxis: {
    type: 'category',
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    splitArea: {
      show: true
    }
  },
  visualMap: {
    min: 0,
    max: 100,
    calculable: true,
    orient: 'horizontal',
    left: 'center',
    bottom: '15%'
  },
  series: [{
    type: 'heatmap',
    data: [],
    label: {
      show: true
    },
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }]
}))

// 获取实时数据
const fetchRealtimeData = async () => {
  try {
    const res = await getRealtimeData()
    realtimeData.value = res.data.map(item => ({
      ...item,
      updateTime: new Date().toLocaleTimeString()
    }))
  } catch (error) {
    console.error('获取实时数据失败:', error)
  }
}

// 获取实时图表数据
const fetchRealtimeChart = async () => {
  try {
    const res = await getRealtimeChart({ type: monitorType.value })
    const { dates, realtime, average } = res.data
    realtimeChartOption.value.xAxis.data = dates
    realtimeChartOption.value.series[0].data = realtime
    realtimeChartOption.value.series[1].data = average
  } catch (error) {
    console.error('获取实时图表数据失败:', error)
  }
}

// 获取告警列表
const fetchAlerts = async () => {
  try {
    const res = await getAlerts()
    alerts.value = res.data
  } catch (error) {
    console.error('获取告警列表失败:', error)
  }
}

// 处理自动刷新
const handleAutoRefreshChange = (val) => {
  if (val) {
    refreshInterval.value = setInterval(() => {
      fetchRealtimeData()
      fetchRealtimeChart()
      fetchAlerts()
    }, 5000)
  } else {
    clearInterval(refreshInterval.value)
  }
}

// 查看全部告警
const handleViewAllAlerts = () => {
  // TODO: 实现查看全部告警的逻辑
}

// 处理告警
const handleAlertAction = (alert) => {
  // TODO: 实现处理告警的逻辑
}

// 保存告警设置
const saveAlertSettings = async () => {
  try {
    await updateAlertSettings(alertSettings.value)
    ElMessage.success('告警设置保存成功')
    alertSettingVisible.value = false
  } catch (error) {
    console.error('保存告警设置失败:', error)
    ElMessage.error('保存告警设置失败')
  }
}

onMounted(() => {
  fetchRealtimeData()
  fetchRealtimeChart()
  fetchAlerts()
  if (autoRefresh.value) {
    handleAutoRefreshChange(true)
  }
})

onUnmounted(() => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
  }
})
</script>

<style lang="scss" scoped>
.realtime-monitor {
  padding: 20px;

  .data-overview {
    margin-bottom: 20px;
  }

  .data-card {
    &.alert {
      border: 1px solid #f56c6c;
      .card-header {
        color: #f56c6c;
      }
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-body {
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin: 10px 0;
      }

      .trend {
        font-size: 14px;
        color: #909399;

        .update-time {
          margin-left: 8px;
          color: #67C23A;
        }
      }
    }
  }

  .chart-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .header-actions {
      display: flex;
      gap: 10px;
      align-items: center;
    }

    .chart-container {
      height: 400px;

      .chart {
        height: 100%;
      }
    }
  }

  .alert-list {
    .alert-item {
      display: flex;
      align-items: center;
      padding: 12px;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      &.high {
        background-color: #fef0f0;
        .el-icon {
          color: #f56c6c;
        }
      }

      &.medium {
        background-color: #fdf6ec;
        .el-icon {
          color: #e6a23c;
        }
      }

      &.low {
        background-color: #f0f9eb;
        .el-icon {
          color: #67c23a;
        }
      }

      .el-icon {
        font-size: 20px;
        margin-right: 12px;
      }

      .alert-content {
        flex: 1;

        .alert-title {
          font-size: 14px;
          color: #303133;
          margin-bottom: 4px;
        }

        .alert-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }

  // 响应式布局
  @media screen and (max-width: 768px) {
    .el-row {
      margin: 0 !important;
    }

    .el-col {
      padding: 0 !important;
    }

    .chart-container {
      height: 300px;
    }
  }
}
</style> 